package com.nettyRpc.provider.netty;

import com.alibaba.fastjson.JSON;
import com.nettyRpc.api.DubboRequest;
import com.nettyRpc.api.DubboResult;
import com.nettyRpc.provider.InvokeSupport;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


/**
 * 监听处理数据 通道- ChannelInboundHandlerAdapter
 */
public class DubboChannelHandler extends ChannelInboundHandlerAdapter {
    /**
     * 通道读取数据事件，监听
     * ChannelHandlerContext(DubboChannelHandler#0, [id: 0x99314047, L:/127.0.0.1:8088 - R:/127.0.0.1:57663])
     * DubboRequest(id=100, className=com.nettyRpc.api.IHelloService, method=hello, args=[Hello World])
     *
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        DubboRequest request = (DubboRequest) msg;
        //根据接口-反射实现，拿到结果
        Object result = new InvokeSupport().invoke(request);
        DubboResult response = new DubboResult();
        response.setId(request.getId());
        response.setData(result);
        System.err.println("服务器回复消息：" + JSON.toJSONString(response));
        ctx.writeAndFlush(response);
        //写回信息
    }

    /**
     * 数据读取完毕事件
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        //完毕
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 通道发生异常事件
        super.exceptionCaught(ctx, cause);
    }
}
